package com.cobo.html;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class MatterEngine {

    private String delimiter = "---";

    public MatterEngine(){

    }

    public MatterEngine(String delimiter){
        this.delimiter = delimiter;
    }

    public FileMeta matter(String content) {
        if (StringUtils.isEmpty(content)) {
            return new FileMeta(null, content);
        }

        String[] split = content.split("\n");
        if (StringUtils.equals(split[0], delimiter)) {
            int endMeta = 0;
            for (int i = 1; i < split.length; i++) {
                if (StringUtils.equals(split[i], delimiter)) {
                    endMeta = i;
                    break;
                }
            }
            if (endMeta == 0) {
                return new FileMeta(null, content);
            }

            Map<String, String> formatter = new HashMap<>();

            for (int i = 1; i < endMeta; i++) {
                if (StringUtils.contains(split[i], "=")) {
                    String[] kv = split[i].split("=");
                    if (kv.length!=2){
                        continue;
                    }
                    formatter.put(kv[0].trim(), kv[1].trim());
                }
            }
            StringBuilder sb = new StringBuilder();
            for (int i = endMeta+1; i < split.length; i++) {
                sb.append(split[i])
                        .append("\n");
            }
            return new FileMeta(formatter, sb.toString());

        }else {
            return new FileMeta(null, content);
        }
    }
}
